
import {padEnd} from "lodash-es"
import checkType from "../checkType/index"

// 按对象属性排序
// order：‘stl'|true从小到大，
interface anyObj {
  [ property: string ]: any
}

interface $prop {
  [ prope: string ]: boolean
}
type c = $prop | string

function sortObj (objArr: anyObj[], prope: (string | anyObj)[] | string, order: boolean | string = true, isPromise: boolean = false) {
  let arr = objArr.sort(<any>((a: anyObj, b: anyObj) => {
    // 如果prope是字符串则直接进行sort
    if (typeof prope == 'string') {
      if (order == 'stl' || order == true) {
        return ~~(a[ prope ] > b[ prope ])
      } else {
        return ~~(b[ prope ] > a[ prope ])
      }
    } else if (checkType.isArray(prope)) {
      // 如果是数组，则接受字符串属性或者对象属性来比较
      // 如果是对象则属性是objArr的某个属性，然后等级从高到低进行排列，属性的值可以为true/false,true为从小到大，false则反之。
      try {
        for (let item of prope) {
          if (checkType.isString(item) && a[ <string>item ] != b[ <string>item ]) {
            return ~~(a[ <string>item ] > b[ <string>item ])
          } else if (checkType.isObj(item) && a[ Object.keys(item)[ 0 ] ] != b[ Object.keys(item)[ 0 ] ]) {
            if ((<any>item)[ Object.keys(item)[ 0 ] ]) {
              return ~~(a[ Object.keys(item)[ 0 ] ] > b[ Object.keys(item)[ 0 ] ])
            } else {
              return ~~(a[ Object.keys(item)[ 0 ] ] < b[ Object.keys(item)[ 0 ] ])
            }
          }
        }
      } catch (error) {
        console.error(error)
        throw new Error('prope参数错误，必须是objArr的属性字符串，或者[string|[]]数组')
      }
    }
  }))
  if (isPromise) {
    return Promise.resolve(arr)
  }
  return arr
}

// [year: string, month: string, day?: string, hours?: string, minutes?: string, seconds?: string, milliseconds?: string]
// 解析时间
//从“2018-02-14 12:12:12"解析到具体时间毫秒或者对象
type $dateparam = [ number, number, number, number?, number?, number?]
function parseTime ({
  value = '',
  dateSeparator = '-',
  timeSeparator = ":"
} = {}) {
  if (!value)
    return console.error(`value不可为空`)

  if (value.includes(' ')) {
    let datetime: any = value.split(' ')
    let _date: any = datetime[ 0 ].split(dateSeparator)
    _date[ 1 ] = _date[ 1 ] - 1
    datetime = [ ..._date, ...datetime[ 1 ].split(timeSeparator) ]
    return new Date(...<$dateparam>datetime)
  }
  // 因为开始必须是年月，所以不能直接解析时间点
  let _date: any = value.split(dateSeparator)
  _date[ 1 ] = _date[ 1 ] - 1
  return new Date(...<$dateparam>_date)
}
// 对文字床度限制
function limitText (str: string, limit: number = 10) {
  let strNew = str + ''
  // 截取文字，并对多余的显示为'...'
  if (strNew.length > ~~limit) {
    strNew = strNew.substr(0, limit - 3)
    strNew = padEnd(strNew, limit, '.')
  }
  // 返回新旧字符串对象
  return {
    strNew,
    str,
    new: strNew,
    old: str
  }
}

// 对title进行更改
function title (str: string) {
  (document.querySelector('title') as HTMLTitleElement).innerText = str
}
export {
  limitText,
  parseTime,
  sortObj,
  anyObj,
  title
}
